import React, { useEffect } from "react";
import "./login.less";
import logo from "../../asstes/images/logo.png";

import { LockOutlined, UserOutlined } from "@ant-design/icons";
import { Button, Checkbox, Form, Input, message } from "antd";
import { reqLogin } from "../../apis/index.ts";
import { useNavigate } from "react-router-dom"; // 引入withRouter
import memoryUtils from "../../utils/memoryUtils.ts";
import storageUtils from "../../utils/storageUtils.ts";

/**
 * 登录的路由组件
 */

function Login() {
  const navigate = useNavigate(); // 获取navigate函数

  const onFinish = async (e) => {
    console.log(e);
    try {
      const result: any = await reqLogin(e.username, e.password);

      console.log("登录成功", result);
      if (result.status == 0) {
        message.success("登录成功");
        memoryUtils.user = result.data;
        storageUtils.saveUser(result.data);
        // 跳转到管理界面
        navigate("/");
      } else {
        message.error(result.msg);
      }
    } catch (error) {
      message.error("登录失败");
    }
  };

  // 验证密码自定义规则
  const validatePwd = (rule, value, fn) => {
    console.log("validatePwd()", rule, value);
    if (!value) {
      fn("密码必须输入");
    } else if (value.length < 4) {
      fn("密码长度不能小于4位");
    } else if (value.length > 12) {
      fn("密码长度不能大于12位");
    } else if (!/^[a-zA-Z0-9_]+$/.test(value)) {
      fn("密码必须是英文、数字或下划线组成");
    } else {
      // 放行
      fn(); // 验证通过
    }
  };

  const user = memoryUtils.user;
  useEffect(() => {
    if (user && user._id) {
      navigate("/");
    }
  }, [user, user._id]);

  return (
    <div className="login">
      <header className="login-header">
        <img src={logo} alt="logo" />
        <h3>React项目: 电商后台管理系统</h3>
      </header>
      <section className="login-content">
        <h5>用户登录</h5>
        <Form
          name="normal_login"
          className="login-form"
          initialValues={{ remember: true }}
          // onSubmit={this.handleSubmit}
          onFinish={onFinish}
        >
          <Form.Item
            name="username"
            rules={[
              // 配置对象
              {
                required: true,
                whitespace: true,
                message: "Please input your Username!",
              },
              {
                min: 4,
                message: "The user name should contain more than 4 characters",
              },
              {
                max: 12,
                message: "The user name should not exceed 12 characters",
              },
              {
                pattern: /^[a-zA-Z0-9_]+$/,
                message:
                  "The username must contain English, digits, or underscores (_)",
              },
            ]}
            initialValue={"admin"}
          >
            <Input
              // prefix  带有前缀图标的 input
              prefix={<UserOutlined className="site-form-item-icon" />}
              placeholder="Username"
            />
          </Form.Item>
          <Form.Item name="password" rules={[{ validator: validatePwd }]}>
            <Input
              prefix={<LockOutlined className="site-form-item-icon" />}
              type="password"
              placeholder="Password"
            />
          </Form.Item>
          <Form.Item>
            <Form.Item name="remember" valuePropName="checked" noStyle>
              <Checkbox>Remember me</Checkbox>
            </Form.Item>

            <a className="login-form-forgot" href="">
              Forgot password
            </a>
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              className="login-form-button"
            >
              Log in
            </Button>
          </Form.Item>
        </Form>
      </section>
    </div>
  );
}
// const wrapLogin = Form.create()(Login)  Antd 5版本已废除

export default Login;
